package com.example.peibei.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.alipay.sdk.app.PayTask;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dingtao.common.bean.PayBanlance;
import com.dingtao.common.bean.PayOrder;
import com.dingtao.common.bean.PayResult;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.OnCallback;
import com.example.peibei.R;
import com.example.peibei.base.Constant;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.CityBean;
import com.example.peibei.service.presenter.ChcekTextPresenter;
import com.example.peibei.service.presenter.ComputePricePresenter;
import com.example.peibei.service.presenter.PaiDanPushPresenter;
import com.example.peibei.service.presenter.PayBalancePresenter;
import com.example.peibei.service.presenter.SendOrderPresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.ui.weight.CEditText;
import com.example.peibei.ui.weight.CenterDialog;
import com.example.peibei.ui.weight.GlideEngine;
import com.example.peibei.ui.weight.MoneyKeyboardDialog;
import com.example.peibei.ui.weight.OnDialogSelectPositionListener;
import com.example.peibei.ui.weight.PayStatusDialog;
import com.example.peibei.ui.weight.SelectDateDialog;
import com.example.peibei.wxapi.WXPayEntryActivity;
import com.linxiao.framework.common.ScreenUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnMoreItemPickListener;
import cn.addapp.pickers.listeners.OnMoreWheelListener;
import cn.addapp.pickers.picker.LinkagePicker;
import cn.addapp.pickers.picker.SinglePicker;
import cn.addapp.pickers.widget.WheelView;

//import com.wildma.pictureselector.PictureSelector;

public class ChooseOrderContent2Activity extends WDActivity {
    @BindView(R.id.et_order)
    EditText et_order;
    @BindView(R.id.tv_city_name)
    TextView tv_city_name;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_pay_text)
    TextView tv_pay_text;
    @BindView(R.id.select_hour)
    TextView select_hour;
    @BindView(R.id.select_time)
    TextView select_time;
    @BindView(R.id.tv_yu_money)
    TextView tv_yu_money;
    @BindView(R.id.iv_pay_icon)
    ImageView iv_pay_icon;
    @BindView(R.id.iv_location)
    ImageView iv_location;

    private int categoryId;
    String imagePathOne = "";
    String imagePathTwo = "";
    String imagePathThree = "";
    private UploadImagePresenter uploadImagePresenter;
    private ChcekTextPresenter chcekTextPresenter;
    private PaiDanPushPresenter pushPresenter;
    private ComputePricePresenter computePricePresenter;
    private SPUtils spUtils;
    private String token;
    private String cityName;
    private String cityCode;
    private String address;
    private String beginTime;
    private String content;
    private String orderTime;
    public AMapLocationClient mLocationClient = null;
    int payType = 2;  //支付类型 0 余额 1 微信  2 支付宝

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_order_content2;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        categoryId = bundle.getInt("categoryId");
        spUtils = new SPUtils(this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);

        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        pushPresenter = new PaiDanPushPresenter(new SendOrderCall());
        chcekTextPresenter = new ChcekTextPresenter(new CheckTextCall());
        computePricePresenter = new ComputePricePresenter(new ComputePrice());

    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.ll_address)
    public void local() {
        getLocalPermission();
    }

    @OnClick(R.id.layout_set_money)
    public void setMoney() {
        MoneyKeyboardDialog dialog = new MoneyKeyboardDialog(this);
        dialog.create(new MoneyKeyboardDialog.OnMoneyListener() {
            @Override
            public void onMoney(String money) {
                tv_money.setText(money);
                computePricePresenter.reqeust("Bearer " + token, money);
            }
        });
    }

    @OnClick(R.id.ll_pay_status)
    public void switchPayType() {
        PayStatusDialog dialog = new PayStatusDialog(this);
        dialog.create(payType,token,"0", new OnCallback<Integer>() {
            @Override
            public void onCall(Integer result) {
                initPayUi(result);
            }
        });
    }

    //初始化支付状态ui
    private void initPayUi(int type) {
        payType = type;
        if (payType == 0) {
            iv_pay_icon.setImageResource(R.mipmap.qianbao_icon);
            tv_pay_text.setText("钱包支付");
        } else if (payType == 1) {
            iv_pay_icon.setImageResource(R.mipmap.wechat_icon);
            tv_pay_text.setText("微信支付");
        } else if (payType == 2) {
            iv_pay_icon.setImageResource(R.mipmap.ali_pay_icon);
            tv_pay_text.setText("支付宝支付");
        }
    }

    @OnClick(R.id.btn_submit)
    public void submit() {
        content = et_order.getText().toString().trim();
        if (content.equals("")) {
            UIUtils.showToastSafe("内容不能为空");
            return;
        }
        if (TextUtils.isEmpty(cityCode) || TextUtils.isEmpty(cityName)) {
            UIUtils.showToastSafe("请选择当前位置");
            return;
        }
        chcekTextPresenter.reqeust("Bearer " + token, content);
    }

    @OnClick(R.id.select_time)
    public void selectTime() {
        showChooseTime();
    }

    @OnClick(R.id.select_hour)
    public void selectHour() {
        showChooseHour();
    }

    private void showChooseTime() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            calendar.getTime();
            times.add(format.format(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_MONTH, +1);
        }
        List<String> times2 = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            times2.add(i + "时");
        }
        SelectDateDialog dialog = new SelectDateDialog(this);
        dialog.setOnDialogSelectPositionListener(new OnDialogSelectPositionListener() {
            @Override
            public void onSelect(int position, int position2) {
                String first = times.get(position);
                String second = times2.get(position2);
                beginTime = first + " " + (second.length() == 2 ? "0" : "") + second.replace("时", ":00:00");
                select_time.setText(first + " " + second);
            }
        });
        dialog.createShow(times, times2);
    }

    private void showChooseHour() {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            times.add((i + 1) + "h");
        }
        SelectDateDialog dialog = new SelectDateDialog(this);
        dialog.setOnDialogSelectPositionListener(new OnDialogSelectPositionListener() {
            @Override
            public void onSelect(int position, int position2) {
                String first = times.get(position);
                orderTime = first;
                select_hour.setText(first);
            }
        });
        dialog.createShow(times, null);
    }


    private static String[] PERMISSIONSLOCAL = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void getLocalPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONSLOCAL,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        // 当所有权限的申请被用户同意之后,该方法会被调用

                        //隐私政策合规
                        AMapLocationClient.updatePrivacyShow(getApplicationContext(), true, true);
                        AMapLocationClient.updatePrivacyAgree(getApplicationContext(), true);
                        //初始化定位
                        try {
                            mLocationClient = new AMapLocationClient(getApplicationContext());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //声明定位回调监听器
                        AMapLocationListener mLocationListener = new AMapLocationListener() {
                            @Override
                            public void onLocationChanged(AMapLocation aMapLocation) {
                                Log.i("answer", aMapLocation.getCity());//城市信息
                                Log.i("answer", aMapLocation.getCityCode());//城市信息
                                address = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict();
                                cityName = aMapLocation.getCity();
                                cityCode = aMapLocation.getCityCode();
                                tv_city_name.setText(cityName);
                                tv_city_name.setVisibility(View.VISIBLE);
                                iv_location.setVisibility(View.GONE);
                                spUtils.putString(SpConstant.CITY_NAME, aMapLocation.getCity());
                                spUtils.putString(SpConstant.CITY_CODE, aMapLocation.getCityCode());
                                CityBean cityBean = new CityBean(aMapLocation.getCity(), aMapLocation.getCityCode());
                                EventBus.getDefault().post(cityBean);
                            }
                        };
                        //设置定位回调监听
                        mLocationClient.setLocationListener(mLocationListener);
                        AMapLocationClientOption option = new AMapLocationClientOption();
                        option.setOnceLocation(true);

                        //给定位客户端对象设置定位参数
                        mLocationClient.setLocationOption(option);
                        //启动定位
                        mLocationClient.startLocation();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        spUtils.putString(SpConstant.CITY_NAME, "");
                        spUtils.putString(SpConstant.CITY_CODE, "");
//                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
//                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        spUtils.putString(SpConstant.CITY_NAME, "");
                        spUtils.putString(SpConstant.CITY_CODE, "");
//                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
//                        getPermission();
                    }

                });
    }

    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            if (imagePathOne.equals("")) {
                imagePathOne = data;
            } else {
                if (imagePathTwo.equals("")) {
                    imagePathTwo = data;
                } else {
                    imagePathThree = data;
                }
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入含有不合法的内容或图片，请遵守用户协议相关内容");
        }
    }


    String id;

    class SendOrderCall implements DataCall<PayOrder> {

        @Override
        public void success(PayOrder data, Object... args) {
            id = data.getId();
            if (payType == 0) {
                if (data.getStatus().equals("0")) {
                    UIUtils.showToastSafe("您的余额不足，请充值");
                } else {
                    payOrderSure(data);
                }
            } else if (payType == 2) {
                String retString = data.getRetString();
                payOrderForAlipay(retString);
            } else {
                payOrderForWx(data);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            e.printStackTrace();
            UIUtils.showToastSafe(e.getDisplayMessage());
        }

    }

    private void payOrderForWx(PayOrder data) {
        SubmitOrderActivity.submitOrderActivity = null;
        WXPayEntryActivity.setOnCallback(new OnCallback<Boolean>() {
            @Override
            public void onCall(Boolean result) {
                if (result) {
                    toDaichuliu();
                } else {
                    Toast.makeText(ChooseOrderContent2Activity.this, "支付失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, WXPayEntryActivity.APP_ID, true);

        // 将应用的appId注册到微信
        wxapi.registerApp(WXPayEntryActivity.APP_ID);

        PayReq req = new PayReq();
        req.appId = data.getAppId();
        req.partnerId = data.getPartnerId();
        req.prepayId = data.getPrePayId();
        req.packageValue = data.get_package();
        req.nonceStr = data.getNonceStr();
        req.timeStamp = data.getTimestamp();
//        req.extData = extData;
        req.sign = data.getSign();

        // 调起微信支付页面
        boolean result = wxapi.sendReq(req);
    }

    private static final int SDK_PAY_FLAG = 1;

    private void payOrderForAlipay(String retString) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ChooseOrderContent2Activity.this);
                Map<String, String> result = alipay.payV2(retString, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toDaichuliu();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        UIUtils.showToastSafe(payResult.getMemo());
                    }
                    break;
                }
            }
        }
    };

    private void toDaichuliu() {

        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("支付中...");
        dialog.show();
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
                UIUtils.showToastSafe("支付成功");
                finish();

                Bundle bundle = new Bundle();
                bundle.putInt("index", 2);
                intent(OrderWaitActivity.class, bundle);
            }
        },3000);

        User loginUser = SpConstant.getLoginUser();
        loginUser.setExistsDispatchOrder(true);
        SpConstant.login(loginUser);

    }

    private void payOrderSure(PayOrder data) {
        String string = spUtils.getString(SpConstant.PAY_PWD);
        if (string.equals("false")) {
            intent(SettingPayPswActivity.class);
        } else {
            showYueDialog(data);
        }
    }

    private void showYueDialog(PayOrder data) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_input_password, null);
        CenterDialog bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog.show();
        ImageView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_money = dialogView.findViewById(R.id.tv_money);
        CEditText cedittext = dialogView.findViewById(R.id.cedittext);
        tv_money.setText("￥" + data.getMoney());
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        cedittext.setOnFinishListener(msg -> {

            PayBalancePresenter payBalancePresenter = new PayBalancePresenter(new DataCall() {
                @Override
                public void success(Object data, Object... args) {
                    toDaichuliu();
                }

                @Override
                public void fail(ApiException data, Object... args) {
                    Toast.makeText(ChooseOrderContent2Activity.this, String.valueOf(args), Toast.LENGTH_SHORT).show();
                }
            });
            PayBanlance payBanlanceOrder = new PayBanlance();
            payBanlanceOrder.setOrderId(data.getOrderId());
            payBanlanceOrder.setPreId(data.getPreId());
            payBanlanceOrder.setType("3");
            payBanlanceOrder.setPayKey(msg);
            payBalancePresenter.reqeust("Bearer " + token, payBanlanceOrder);
        });
    }

    class CheckTextCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
//            String filePath = imagePathOne;
//            if (!imagePathTwo.equals("")) {
//                filePath = imagePathOne + "," + imagePathTwo;
//            }
//            if (!imagePathThree.equals("")) {
//                filePath = imagePathOne + "," + imagePathTwo + "," + imagePathThree;
//            }
//            if (TextUtils.isEmpty(filePath)) {
//                UIUtils.showToastSafe("图片不能为空");
//                return;
//            }
            String money = tv_money.getText().toString().trim();
            if (TextUtils.isEmpty(money)) {
                UIUtils.showToastSafe("金额不能为空");
                return;
            }
            if (TextUtils.isEmpty(address)) {
                UIUtils.showToastSafe("请选择活动地址");
                return;
            }
            if (TextUtils.isEmpty(beginTime)) {
                UIUtils.showToastSafe("请选择开始时间");
                return;
            }
//            if (TextUtils.isEmpty(orderTime)) {
//                UIUtils.showToastSafe("请选择活动时长");
//                return;
//            }
            pushPresenter.reqeust("Bearer " + token, address, beginTime, String.valueOf(categoryId),
                    cityCode, cityName, content,
"",
//                    orderTime,
                    String.valueOf(payType),
                    money, "-1",
                    ""
//                    filePath
            );


        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }

    }

    class ComputePrice implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            tv_yu_money.setText("￥"+data);

        }

        @Override
        public void fail(ApiException e, Object... args) {

        }

    }

    @Override
    protected void destoryData() {

    }
}
